package cn.thornbird.orgsync.config;

import cn.thornbird.orgsync.util.CookieUtil;
import cn.thornbird.orgsync.util.EncryptUtil;
import cn.thornbird.orgsync.util.WebUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

@Component
@WebFilter(filterName = "csrfFilter", urlPatterns = "/*")
@Order(1)
public class CsrfFilter implements Filter {

    public static final String CSRF_TOKEN_NAME = "XSRF-TOKEN";

    public static final String REQUEST_CSRF_TOKEN_NAME = "X-XSRF-TOKEN";

    public static final Set<String> ALLOWED_URIS = new HashSet<>(Arrays.asList(new String[] {
            "index", "sign_in", "sign_up", "reset_password", "api"
    }));

    public static final Set<String> ALLOWED_METHODS = new HashSet<>(Arrays.asList(new String[] {
            "GET", "HEAD", "TRACE", "OPTIONS"
    }));

    private static List<String> apiURIList;

    private final WebApplicationContext applicationContext;

    @Value("${springfox.documentation.enabled}")
    private Boolean springfoxDocumentationEnabled;

    public CsrfFilter(WebApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
        createApiUriList();
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();
        String[] uris = requestURI.toLowerCase().split("/");
        if (uris.length < 2 || !ALLOWED_URIS.contains(uris[1])) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        boolean isApiRequest = WebUtil.isApiRequest(requestURI);
        boolean isApiExportRequest = WebUtil.isApiExportRequest(requestURI);
        boolean isAllowedApiRequest = WebUtil.isAllowedApiRequest(requestURI);
        if (isApiRequest && !containsURI(requestURI)) {
            WebUtil.writeHttpStatusToResponse(response, HttpStatus.NOT_FOUND);
            return;
        }

        if (request.getMethod().equals(RequestMethod.GET.name())) {
            if (CookieUtil.getCookieValue(request, CSRF_TOKEN_NAME) == null) {
                String token = EncryptUtil.csrfToken(request);
                CookieUtil.setCookieValue(response, CSRF_TOKEN_NAME, token);
            }
        } else if (!ALLOWED_METHODS.contains(request.getMethod())) {
            if (springfoxDocumentationEnabled == null || !springfoxDocumentationEnabled) {
                String originalToken = CookieUtil.getCookieValue(request, CSRF_TOKEN_NAME);
                originalToken = originalToken == null ? "" : originalToken;
                String token = request.getHeader(REQUEST_CSRF_TOKEN_NAME);
                if (token == null) {
                    token = request.getParameter(REQUEST_CSRF_TOKEN_NAME);
                }
                token = token == null ? "" : token;
                if (!token.equals(originalToken)) {
                    WebUtil.writeHttpStatusToResponse(response, HttpStatus.FORBIDDEN);
                    return;
                }
            }
        }

        if (!isApiRequest || isAllowedApiRequest || checkLogined(response, isApiExportRequest)) {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    private boolean checkLogined(HttpServletResponse response, boolean isApiExportRequest) throws IOException {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        boolean logined = authentication != null && !(authentication instanceof AnonymousAuthenticationToken);
        if (!logined) {
            if (isApiExportRequest) {
                WebUtil.writeExcelErrorMessageToResponse(response, HttpStatus.UNAUTHORIZED.getReasonPhrase());
            } else {
                WebUtil.writeHttpStatusToResponse(response, HttpStatus.UNAUTHORIZED);
            }
        }
        return logined;
    }

    private void createApiUriList() {
        if (apiURIList != null) {
            return;
        }

        RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
        Map<RequestMappingInfo, HandlerMethod> methodMap = mapping.getHandlerMethods();
        apiURIList = new ArrayList<>();
        for (RequestMappingInfo info : methodMap.keySet()) {
            Set<String> uris = info.getPatternsCondition().getPatterns();
            for (String uri : uris) {
                String[] parts = uri.split("/");
                if (parts.length > 1 && parts[1].equals(WebUtil.API_PREFIX)) {
                    apiURIList.add(uri.toLowerCase());
                }
            }
        }
    }

    private boolean containsURI(String uri) {
        boolean result = false;
        String[] uriParts = uri.toLowerCase().split("/");
        for (String apiURI : apiURIList) {
            String[] parts = apiURI.split("/");
            if (parts.length != uriParts.length) {
                continue;
            }
            for (int i = 0; i < parts.length; i++) {
                String a = parts[i];
                String b = uriParts[i];
                if (a.startsWith("{") && a.endsWith("}")) {
                    b = a;
                }
                if (!a.equals(b)) {
                    break;
                }
                if (i == parts.length - 1) {
                    result = true;
                }
            }
            if (result) {
                break;
            }
        }
        return result;
    }

}
